package postgressql

import (
	"context"
	"fmt"
	"log"

	"torrent/models"

	"github.com/jackc/pgx/v5/pgxpool"
)

type Pool struct {
	PgPool *pgxpool.Pool
}

const qweryInsert = `INSERT INTO user_google (email, family_name, given_name, nik, locale, full_name, verified_email) VALUES ($1, $2, $3, $4, $5, $6, $7)`

const selectUser = `SELECT (verified_email) FROM user_google WHERE email = $1`

const Insertfavorite = `INSERT INTO favorite (user_id,title,url) VALUES ($1,$2,$3) RETURNING favorite_id`

func NewPool(URIDB string) (*Pool, error) {
	dbpool, err := pgxpool.New(context.Background(), URIDB)
	if err != nil {
		return nil, fmt.Errorf("unable to create connection pool: %v", err)

	}
	return &Pool{
		PgPool: dbpool,
	}, nil
}

func (p *Pool) InsertUser(user models.UserGoogle) error {
	ctx := context.Background()
	var us models.UserGoogleDB
	tx, err := p.PgPool.Begin(ctx)
	if err != nil {
		tx.Rollback(ctx)
		return fmt.Errorf("error beginning transaction: %s", err)
	}
	log.Print(user)
	_, err = tx.Exec(ctx, qweryInsert, user.Email, user.FamilyName, user.GivenName, user.Name, user.Locale, user.Name, user.VerifiedEmail)

	log.Print("Insert :", us)
	if err != nil {
		tx.Rollback(ctx)
		return fmt.Errorf("error inserting user data: %s", err)
	}
	err = tx.Commit(ctx)
	if err != nil {
		tx.Rollback(ctx)
		return fmt.Errorf("error committing transaction: %s", err)
	}
	return nil
}

func (p *Pool) CheckUserReg(user models.UserGoogle) (bool, error) {
	ctx := context.Background()
	var us models.UserGoogleDB
	err := p.PgPool.QueryRow(ctx, selectUser, user.Email).Scan(&us.VerifiedEmail)
	log.Print(us)
	if err != nil {
		return us.VerifiedEmail, fmt.Errorf("not reg user %v", err)
	}

	if !us.VerifiedEmail {
		return us.VerifiedEmail, fmt.Errorf("not valid email %v", us)
	}
	return us.VerifiedEmail, nil
}
func (p *Pool) Insertfavorite(f models.Favorite) (string, error) {
	ctx := context.Background()
	tx, err := p.PgPool.Begin(ctx)
	if err != nil {
		tx.Rollback(ctx)
		return "", fmt.Errorf("error beginning transaction: %s", err)
	}
	var userId string
	if err = tx.QueryRow(ctx, Insertfavorite, f.UserId, f.Title, f.Url).Scan(&userId); err != nil {
		return "", err
	}
	return userId, nil
}
